package com.easyoffer.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.easyoffer.common.util.BlackIpUtil;
import com.easyoffer.common.util.NetUtils;
import com.easyoffer.constant.UserConstant;
import com.easyoffer.model.entity.User;
import com.easyoffer.model.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.Console;
import java.io.IOException;

/**
 * 黑名单ip、封号用户访问控制
 */
@WebFilter(urlPatterns = "/*", filterName = "blacklistAccessFilter")
public class BlacklistAccessFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ipAddress = NetUtils.getIpAddress((HttpServletRequest) servletRequest);
        UserVO userVO = null;
        if (StpUtil.isLogin())
            userVO = (UserVO) StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);

        if (BlackIpUtil.isBlackIp(ipAddress) ||
                (userVO != null && UserConstant.BAN_ROLE.equals(userVO.getUserRole())) ) {
            servletResponse.setContentType("text/json;charset=UTF-8");
            servletResponse.getWriter().write("{\"errorCode\":\"-1\",\"errorMsg\":\"黑名单IP，禁止访问\"}");
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
